#include "stdafx.h"
#include "Client.h"

#include "Timer.h"

Client::Client(Manager *pManager, ClientGroup eGroup)
{
	m_pManager = pManager;
	m_eGroup = eGroup;

	m_hProcessSemaphore = CreateSemaphore(NULL, 0, 1, NULL);

	m_fProcessTime = 0.0f;
	m_fWaitTime = 0.0f;
	m_fSmokeTime = 0.0f;
	m_ulNumCigarettes = 0ul;
}

Client::~Client()
{
	CloseHandle(m_hProcessSemaphore);
}

void Client::Process()
{
	Timer timer;

	m_fProcessTime = 0.0f;
	m_fWaitTime = 0.0f;
	m_fSmokeTime = 0.0f;
	m_ulNumCigarettes = 0ul;

	while (m_fProcessTime < CLIENT_WORK_TIME)
	{
		timer.GetElapsedSeconds();

		// Oczekiwanie na zasoby
		switch (m_eGroup)
		{
		case ClientGroupWithPaper:
			m_pManager->GetResource(1);
			m_pManager->GetResource(2);
			break;
		case ClientGroupWithTobacco:
			m_pManager->GetResource(0);
			m_pManager->GetResource(2);
			break;
		case ClientGroupWithMatch:
			m_pManager->GetResource(0);
			m_pManager->GetResource(1);
			break;
		}

		m_fWaitTime += timer.GetElapsedSeconds();

		// Palenie
		Sleep(CLIENT_SMOKE_TIME);

		m_fSmokeTime += timer.GetElapsedSeconds();

		m_ulNumCigarettes++;

		m_fProcessTime = m_fWaitTime + m_fSmokeTime;
	}

	ReleaseSemaphore(m_hProcessSemaphore, 1, NULL);
}

void Client::RunThread()
{
	HANDLE hThread = CreateThread(
		NULL,
		0,
		Client::ThreadFunction,
		(LPVOID)this,
		0,
		NULL
		);
}

DWORD WINAPI Client::ThreadFunction(LPVOID param)
{
	Client* m_pClient = (Client*)param;
	m_pClient->Process();

	return 0;
}

void Client::PrintRaport()
{
	printf(
		"Palacz [%d]: %d papierosow, czas razem: %f, czekanie: %f, palenie: %f\n",
		m_eGroup,
		m_ulNumCigarettes,
		m_fProcessTime,
		m_fWaitTime,
		m_fSmokeTime
	);
}